package spiders

import (
	"dianping_sol/config"
	"dianping_sol/db"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/PuerkitoBio/goquery"
	"log"
	"net/http"
	"os"
	"strings"
)

// InitGR 获取gr,类别,地区,只获取行政区,其他不管
func InitGR(initUrl, c string) error {
	if config.Conf.Init.Successful {
		return nil
	}
	req, err := http.NewRequest("GET", initUrl, nil)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", config.Conf.DianPing.UserAgent)
	req.Header.Set("Cookie", config.Conf.DianPing.Cookie)
	req.Header.Set("Host", config.Conf.DianPing.Host)
	req.Header.Set("sec-ch-ua-platform", config.Conf.DianPing.Sec)
	req.Header.Set("Accept", config.Conf.DianPing.Accept)
	client := &http.Client{}
	resp, err := client.Do(req)
	defer resp.Body.Close()
	if resp.StatusCode == 200 {
		//r, _ := io.ReadAll(resp.Body)
		//fmt.Println(string(r))
		doc, err := goquery.NewDocumentFromReader(resp.Body)
		if err != nil {
			return err
		}
		base := doc.Find(`.navigation`)
		gMap := make(map[string]string)
		base.Find(`#classfy a`).Each(func(i int, selection *goquery.Selection) {
			g := strings.TrimSpace(selection.Text())
			attr, exists := selection.Attr(`data-cat-id`)
			if exists {
				gMap[g] = attr
			}
		})
		rMap := make(map[string]string)
		//base.Find("#bussi-nav a").Each(func(i int, selection *goquery.Selection) {
		//	r := strings.TrimSpace(selection.Text())
		//	attr, exists := selection.Attr(`data-cat-id`)
		//	if exists {
		//		rMap[r] = attr
		//	}
		//})
		base.Find("#region-nav a").Each(func(i int, selection *goquery.Selection) {
			r := strings.TrimSpace(selection.Text())
			attr, exists := selection.Attr(`data-cat-id`)
			if exists {
				rMap[r] = attr
			}
		})
		//base.Find("#metro-nav a").Each(func(i int, selection *goquery.Selection) {
		//	r := strings.TrimSpace(selection.Text())
		//	attr, exists := selection.Attr(`data-cat-id`)
		//	if exists {
		//		rMap[r] = attr
		//	}
		//})

		//absolute := true
		//if len(gMap) == 37 {
		//	absolute = false
		//}
		//if len(rMap) == 65 {
		//	absolute = false
		//}
		//if absolute {
		//	fmt.Println(`Incomplete data, waiting for retry`)
		//	time.Sleep(10 * time.Second)
		//	_ = InitGR(initUrl, c)
		//}
		if len(gMap) == 0 || len(rMap) == 0 {
			panic(fmt.Errorf(`init error`))
		}
		for gName, g := range gMap {
			for rName, r := range rMap {
				grp := &db.GRP{
					C:     c,
					G:     g,
					GName: gName,
					R:     r,
					RName: rName,
					P:     "",
					N:     "",
				}
				err := db.G_DB.Create(grp).Error
				if err == nil {
					log.Printf(`insert success %+v`, grp)
				}

			}
		}
		// 写回配置文件
		config.Conf.Init.Successful = true
		if err := writeConf(config.Conf); err != nil {
			panic(err)
		}
	}
	return nil
}

// 写回配置文件

func writeConf(conf config.Config) error {
	// 打开文件
	file, err := os.OpenFile("config.toml", os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// 编码为TOML格式并写入文件
	if err := toml.NewEncoder(file).Encode(conf); err != nil {
		return err
	}
	return nil

}
